package org.lqk.file.transfer.server.framework;

import io.netty.channel.ChannelHandlerContext;

import org.lqk.file.transfer.file.FileStorage;
import org.lqk.file.transfer.protocol.CmdCode;
import org.lqk.file.transfer.protocol.RemotingCommand;
import org.lqk.file.transfer.server.processor.FileSegmentRequestProcessor;
import org.lqk.file.transfer.server.processor.FileTaskRequestProcessor;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2015/8/26.
 */
public class FileRequestProcessorDispatcher {
	private ConcurrentHashMap<String, FileStorage> fileTable = new ConcurrentHashMap<>();
	private final HashMap<Integer,FileRequestProcessor> processorTable = new HashMap<Integer, FileRequestProcessor>();
	private final String baseDir;

	public FileRequestProcessorDispatcher(String baseDir) {
		this.baseDir = baseDir;
//		ExecutorService es = Executors.newCachedThreadPool();
		// this.registProcessor(1, new DefaultProcessor(), es);
//		FileTaskRequestProcessor processor = new FileTaskRequestProcessor(baseDir);
		FileRequestProcessor fileTaskRequestProcessor = new FileTaskRequestProcessor(fileTable,baseDir, CmdCode.File_Task.getCode());
		FileRequestProcessor fileSegmentRequestProcessor = new FileSegmentRequestProcessor(fileTable,baseDir,CmdCode.File_Segment.getCode());
		processorTable.put(fileTaskRequestProcessor.getCmdCode(), fileTaskRequestProcessor);
		processorTable.put(fileSegmentRequestProcessor.getCmdCode(), fileSegmentRequestProcessor);
	}
	
	/**
	 * 处理请求消息
	 * 
	 * @param ctx
	 * @param command
	 */
	public void processCommand(final ChannelHandlerContext ctx, RemotingCommand command) {

		final FileRequestProcessor processor = processorTable.get(command.getCmdCode());

		if (processor != null) {
			// 创建任务
			Runnable runnable = () -> {
				try {
					// 拿到处理器进行处理
					RemotingCommand response = processor.process(command);

					if (!command.isRpcOneway()) {
						if (response != null) {
							response.setOpaque(command.getOpaque());
							ctx.writeAndFlush(response);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};

			ctx.executor().submit(runnable);
			
//			try {
//				// 将任务放入线程池
//				pair.getObject2().submit(runnable);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
		} else {
			// TODO无法处理的请求
		}
	}
}
